package com.jason.www;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

import static java.util.Objects.nonNull;

/**
 * 弃用TransportClient 建议实用 RestClient（HighLevelClient LowLevelClient）
 */
public class ElasticsearchTest3 {
    private static final String HOST = "127.0.0.1";
    private static final int PORT = 9200;
    private static final String SCHEMA = "http";
    private static HttpHost HTTP_HOST = new HttpHost(HOST,PORT,SCHEMA);
    private static RestClientBuilder builder;
    private static RestClient restClient;
    private static RestHighLevelClient restHighLevelClient;


    @Before
    public void initRestClient(){
        builder = RestClient.builder(HTTP_HOST);
        restClient = builder.build();
        restHighLevelClient = new RestHighLevelClient(builder);
    }

    @After
    public void close() {
        if (nonNull(restClient) && nonNull(restHighLevelClient)) {
            try {
                restClient.close();
                restHighLevelClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void getRestHighLevelClient() throws IOException {
        System.out.println("LowLevelClient:" + restClient.getNodes());
        System.out.println("HighLevelClient:" + restHighLevelClient.search(new SearchRequest(), RequestOptions.DEFAULT));
    }
}
